#include "stockmodel.h"
#include <QDateTime>
#include <QApplication>
#include <QVersionNumber>
#include <QStandardPaths>
#include <QDir>
//#include "classes.h"
#include "common.h"

StockListModel::StockListModel(QObject *parent)
    : QAbstractListModel{parent}
{
    readFile();
}

StockListModel::~StockListModel()
{ }

int StockListModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return static_cast<int>(m_recordData.stock_infomation.size());
}

int StockListModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return 1;
}

QHash<int, QByteArray> StockListModel::roleNames() const
{
    return {
        {ROLE_CODE, "code"} ,
        {ROLE_NAME, "name"} ,
        {ROLE_UPPRICE, "up_price"} ,
        {ROLE_PRICE, "price"} ,
        {ROLE_DOWNPRICE, "down_price"}
    };
}

QVariant StockListModel::data(int row, int column, int role) const
{
    return data(index(row, column), role);
}

QVariant StockListModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < 0 || index.row() >= m_recordData.stock_infomation.size())
    {
        return QVariant();
    }
    const StockRecord& d = m_recordData.stock_infomation[index.row()];

    if (role == DataType::ROLE_CODE)
    {
        return d.code;
    }
    else if(role == DataType::ROLE_NAME)
    {
        return d.name;
    }
    else if(role == DataType::ROLE_UPPRICE)
    {
        return d.up_price;
    }
    else if(role == DataType::ROLE_PRICE)
    {
        return d.price;
    }
    else if(role == DataType::ROLE_DOWNPRICE)
    {
        return d.down_price;
    }

    return QVariant();
}

Qt::ItemFlags StockListModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;

    return QAbstractItemModel::flags(index);
}

QVariant StockListModel::headerData(int section, Qt::Orientation orientation,
                               int role) const
{
    return QVariant();
}

bool StockListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    Q_UNUSED(role)

    //将界面修改的值进行保存
    if (index.isValid()) {
        const int row = index.row();
        switch(role)
        {
        case DataType::ROLE_CODE:
            m_recordData.stock_infomation[row].code = value.toInt();
            break;
        case DataType::ROLE_NAME:
            m_recordData.stock_infomation[row].name = value.toString();
            break;
        case DataType::ROLE_UPPRICE:
            m_recordData.stock_infomation[row].up_price = value.toString();
            break;
        case DataType::ROLE_PRICE:
            m_recordData.stock_infomation[row].price = value.toString();
            break;
        case DataType::ROLE_DOWNPRICE:
            m_recordData.stock_infomation[row].down_price = value.toString();
            break;
        default:
            break;
        }

        //发送信号触发刷新
        emit dataChanged(index, index/*, QVector<int>() << role*/);
        return true;
    }
    return false;
}

void StockListModel::doInit()
{
    emit signalCurrentCode(m_recordData.current_stock_code);
}

void StockListModel::doSetCurrent(int code)
{
    m_recordData.current_stock_code = code;
    saveFile();
    emit signalCurrentCode(code);
}

void StockListModel::doDeleteData(int code, int row)
{
    beginResetModel();
    for(int idx = 0; idx < m_recordData.stock_infomation.size(); idx++)
    {
        if(m_recordData.stock_infomation[idx].code == code && row == idx) {
            m_recordData.stock_infomation.removeAt(idx);
            break;
        }
    }
    endResetModel();
    emit layoutChanged();
    saveFile();
}

void StockListModel::doRecordData(int code, QString name, float upPrice, float price, float downPrice)
{
    auto iter = std::find_if(m_recordData.stock_infomation.begin(), m_recordData.stock_infomation.end(), [&code](StockRecord record){
        return (record.code == code);
    });
    if(iter != m_recordData.stock_infomation.end())
        return;

    beginResetModel();
    StockRecord record;
    record.code = code;
    record.name = name;
    record.up_price = QString::number(upPrice, 'f', 3);
    record.price =  QString::number(price, 'f', 3);
    record.down_price = QString::number(downPrice, 'f', 3);
    m_recordData.stock_infomation.append(record);
    endResetModel();
    emit layoutChanged();
    saveFile();
}

void StockListModel::readFile()
{
    QFile json(QApplication::applicationDirPath() + "/data.json");
    if(!json.exists())
        qWarning()<<"ERROR: data.json is not exist";
    if(json.open(QIODevice::ReadOnly))
    {
        m_recordData.fromJson(json.readAll());
        json.close();
    }
}

void StockListModel::saveFile()
{
    QFile json(QApplication::applicationDirPath() + "/data.json");
    if(json.exists())
        json.remove();
    if(json.open(QIODevice::WriteOnly))
    {
        json.write(QSerializer::toByteArray(m_recordData.toJson()));
        json.close();
    }
}

